<?php
namespace app\api\controller;
use think\Db;
class K extends Common{ //K计划 需验证登陆
    public function _empty($name){
        die('非法访问！你的IP已被监控！');
    }
    private function k_zt(){    //私有方法 判断当前K计划状态
        $setting = $this->setting;  //系统参数
        $lun=db('k_lun')->where('zt','<>','3')->order('lun desc')->find();
        $k['lun']=$lun;

        $k_times = explode(',',$setting['k_times']);
        $now_time = time();
        $k_times_arr=[];    //今天+明天的预计时间戳
        //算出今天+明天的时间戳
        foreach ($k_times as $k_time) {
            // dump($k_time);
            $this_time = strtotime($k_time);
            array_push($k_times_arr,$this_time);
            $this_date = date('Y-m-d H:i:s',$this_time);
            $tomorrow_time = strtotime($this_date.' +1 day');
            array_push($k_times_arr,$tomorrow_time);
        }
        //对时间戳排序并判断
        sort($k_times_arr);
        $k['times']=$k_times_arr;   //今天+明天的时间戳 从小到大排序
        $k['time']=false;           //当前进行中的/下轮抢单开始时间
        $k['zt']=false;             //0等待中，1抢单中，2抢单结束清算中，3已结束，4人数不够等下轮
        for ($i=0; $i<count($k_times_arr); $i++) {
            if($now_time < $k_times_arr[$i]){ //没到时间
                $k['time'] = $k_times_arr[$i];
                $k['zt']=$lun&&($lun['zt']==0||$lun['zt']==4)?$lun['zt']:0;
                break;
            }elseif($now_time <= $k_times_arr[$i]+$setting['k_time_qiang']){  //已到时间 但还没过抢单时间
                $k['time'] = $k_times_arr[$i];
                $k['zt']=1;
                break;
            }elseif($now_time <= $k_times_arr[$i]+$setting['k_time_qiang']+$setting['k_delay']){  //已到时间 但还没过延时结算时间
                if($lun && $lun['zt']==4 && time()-$lun['etime']<600){
                    //如果人数不够下 提前结算完成（延时结算时间内已无未到账，提前结算了，这时zt=4）且上次结算完成时间在10分钟内
                    //zt=2时就会执行结算方法，避免人数不足时，多次触发结算方法lun_use多加，10分钟内触发人数不足的结算完成不再执行结算
                    continue;   //计算下一个时间
                }else{
                    //如果还未结算完成
                    $k['time'] = $k_times_arr[$i];
                    $k['zt']=2;
                    break;  //跳出for循环
                }
            }elseif($lun && $lun['zt']==2){ //已到时间 还在结算中
                $k['time'] = $k_times_arr[$i];
                $k['zt']=2;
                break;
            }
            if($i==count($k_times_arr)-1){    //还没找出来报异常
                return ['zt'=>0,'k'=>$k];
                break;
            }
            // 判断下一轮时间..
        }
        //修正轮次状态 为1/2/4,状态3在结算完成后修改
        if($lun && $lun['zt']<>$k['zt']){
            $ret_xiulun = db('k_lun')->where('lun',$lun['lun'])->update([
                'zt'=>$k['zt'],
                'stime'=>$lun['stime']?:time()
            ]);
            if($ret_xiulun){
                $lun['zt']=$k['zt'];
                $k['lun']=$lun;
            }
        }
        return ['zt'=>1,'k'=>$k];
    }
    public function index(){    //首页 基础信息请求
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数
        // if($userinfo['uname']=="15555555555"){
        //     //调用结算 记入本地日志
        //     $ret_jiesuan = $this->jiesuan_do();
        //     $logk = fopen("logk.txt", "a");    //会写在网站根目录public/下
        //     fwrite($logk, date("Y-m-d H:i:s",time())." ".$ret_jiesuan["zt"]." ".$ret_jiesuan["msg"]." ".$ret_jiesuan["lun"]."\r\n");
        //     fclose($logk);
        // }
        //业务处理
        $lun=db('k_lun')->where('zt','<>','3')->order('lun desc')->find();
        $kuser = db('k_user')->where('uid',$userinfo['id'])->find();
        if(!$kuser){
            $kuser=[
                'uid'=>$userinfo['id'],
                'uname'=>$userinfo['uname'],
                'tname'=>$userinfo['tname'],
                'time'=>time(),
                'gusd'=>0.00,
                'lastlun'=>'',
                'sumdan'=>0,
                'sumtou'=>0,
                'sumdong'=>0
            ];
        }
        apifasong(['zt'=>'1','kuser'=>$kuser,'lun'=>$lun?:'','nowtime'=>time(),'setting'=>apisettingbaseinfo($setting)]);
    }
    public function qiang(){    //执行抢单
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        //判断K计划状态
        $k_zt = $this->k_zt();
        if($k_zt['zt']<>1){
            apifasong(['zt'=>'0','msg'=>'K计划状态获取失败']);
        }
        if($k_zt['k']['zt']<>1){
            if($k_zt['k']['zt']==0){
                apifasong(['zt'=>'0','msg'=>'还未开始']);
            }elseif($k_zt['k']['zt']==2){
                apifasong(['zt'=>'0','msg'=>'抢单已结束，结算中...']);
            }elseif($k_zt['k']['zt']==4){
                apifasong(['zt'=>'0','msg'=>'还未开始（上轮人数不足'.$setting['k_disable'].'人，下轮继续）']);
            }else{
                apifasong(['zt'=>'0','msg'=>'K计划状态获取失败']);
            }
        }
        //验证本轮已参与单量
        $sumdan = db('k_true_in')->where('lun',$k_zt['k']['lun']['lun'])->count();
        if($sumdan>=$setting['k_minge']){
            apifasong(['zt'=>'0','msg'=>'抢单失败，本轮单量已被抢完']);
        }
        //验证上次提交（为保证上笔以太已处理完成，不多点击，间隔时间不小于600秒）
        $shangci = db('k_true_in')->where('uid',$userinfo['id'])->order('time desc')->find();
        if($shangci && (time()-$shangci['time'])<600){
            apifasong(['zt'=>'0','msg'=>'相邻两次抢单不得小于600秒']);
        }
        //查询最新ome+eth+gusd余额
        $ome = round($setting['k_ome']*$setting['k_gusd']/100,2);
        if($userinfo['ome']<$ome){
            apifasong(['zt'=>'0','msg'=>'OME余额'.$userinfo['ome'].'，不足'.$ome.'个！']);
        }
        $adeth = db('adeth')->where('uname',$userinfo['uname'])->find();
        $ret_eth = json_decode(@file_get_contents(config('coin_host2') . 'getBalance/?address=' . $adeth['address'].'&type=eth'),true);
        $ret_gusd = json_decode(@file_get_contents(config('coin_host2') . 'getBalance/?address=' . $adeth['address'].'&Contractaddress=' . config('con_gusd') . '&type=gusd'),true);
        if(!$ret_eth || !isset($ret_eth['status']) || $ret_eth['status']<>1 || !isset($ret_eth['balance'])){
            apifasong(['zt'=>'0','msg'=>'ETH余额获取失败']);
        }
        if(!$ret_gusd || !isset($ret_gusd['status']) || $ret_gusd['status']<>1 || !isset($ret_gusd['balance'])){
            apifasong(['zt'=>'0','msg'=>'GUSD余额获取失败']);
        }
        $true_eth = round($ret_eth['balance'],8);
        $true_gusd = round($ret_gusd['balance'],8);
        db('adeth')->where('uname',$userinfo['uname'])->update([
            'eth'=>$true_eth,
            'gusd'=>$true_gusd,
        ]);
        if($true_eth<0.004){
            apifasong(['zt'=>'0','msg'=>'ETH余额'.$true_eth.'，不足0.004个！']);
        }elseif($true_gusd<$setting['k_gusd']){
            apifasong(['zt'=>'0','msg'=>'GUSD余额'.$true_gusd.',不足'.$setting['k_gusd'].'个！']);
        }

        //接口执行转账
        $urlqb=config('coin_host2').'sendTransaction';
        $params['type']='gusd';
        $params['contract']=config('con_gusd');
        $params['from']=$adeth['address'];
        // $params['nonce']='';
        $params['key']=$adeth['key'];
        $params['to']=$setting['k_address'];
        $params['value']=$setting['k_gusd'];
        $params['gas']=20;  //为保障到账速度 提高一倍手续费
        
        $retqb=http($urlqb,$params,'GET',10);
        if(!$retqb){
            apifasong(['zt'=>'0','msg'=>'抢单失败1']);
        }
        $retqb=json_decode($retqb,true);
        if(!isset($retqb['status']) || $retqb['status']<>1 || !isset($retqb['hash'])){
            apifasong(['zt'=>'0','msg'=>'抢单失败2']);
        }
        $chaoshi=0;
        if($k_zt['k']['time']+$setting['k_time_qiang']+5<time()){ //抢单结束后5秒才有处理出结果，此时有可能结算程序已运行，可能导致漏单
            $chaoshi=1;
        }
        //插入数据库
        Db::startTrans();   // 启动事务-------------
        $ret_k_true_in=db('k_true_in')->insertGetId([
            'uid'=>$userinfo['id'],
            'uname'=>$userinfo['uname'],
            'money'=>$setting['k_gusd'],
            'time'=>time(),
            'from'=>$adeth['address'],
            'to'=>$setting['k_address'],
            // 'uptime'=>'',
            'hash'=>$retqb['hash'],
            // 'nonce'=>'',
            // 'blocknumber'=>'',
            // 'gasused'=>'',
            'status'=>3,
            'lun'=>$k_zt['k']['lun']['lun'],
            'chaoshi'=>$chaoshi,
        ]);
        $ret_ome = db('user')->where('id',$userinfo['id'])->setDec('ome',$ome);
        $ret_ome1 = ome1($userinfo,'-'.$ome,'other');
        $log_ome = mylog('ome',$userinfo['uname'],'k','',$userinfo['ome'],'-'.$ome,'K计划抢单',$ret_k_true_in,'');
        if(!db('k_user')->where('uid',$userinfo['id'])->find()){
            $ret_user = db('k_user')->insert([
                'uid'=>$userinfo['id'],
                'uname'=>$userinfo['uname'],
                'tname'=>$userinfo['tname'],
                'time'=>time()
            ]);
        }
        if($ret_k_true_in && $ret_ome && $ret_ome1 && $log_ome){
            Db::commit();       // 提交事务-------------
            if($chaoshi==0){
                apifasong(['zt'=>'1','msg'=>'抢单成功，稍后请查询到账情况']);
            }else{
                apifasong(['zt'=>'1','msg'=>'由于转账时间超时，抢单失败，稍后请查询到账情况']);
            }
        }else{
            Db::rollback();     // 回滚事务-------------
            $error=[];
            $error['time']=date('Y-m-d H:i:s');
            $error['url']='/api/k/qiang:185';
            $error['note1']='K计划抢单错误';
            $error['note2']='hash:'.$retqb['hash'];
            $error['note3']='用户：'.$userinfo['uname'].'ret_k_true_in.ret_ome.log_ome='.$ret_k_true_in.$ret_ome.$log_ome;
            db('error')->insertGetId($error);
            apifasong(['zt'=>'0','msg'=>'抢单失败3']);
        }
    }
    public function jiesuan(){  //用户触发结算
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数
        //调用结算 记入本地日志
        $ret_jiesuan = $this->jiesuan_do();
        if($ret_jiesuan && $ret_jiesuan['zt']<=2){
            $logk = fopen("logk.txt", "a");    //会写在网站根目录public/下
            fwrite($logk, date("Y-m-d H:i:s",time())." 执行状态".$ret_jiesuan["zt"]."，".$ret_jiesuan["msg"]."，第".$ret_jiesuan["lun"]."轮\r\n");
            fclose($logk);
        }
        //如果结算完成 且参与了 返回结算结果
        $lun=db('k_lun')->where('zt','in','3,4')->order('lun desc')->find();
        if(!$lun){
            apifasong(['zt'=>'0','msg'=>'触发结算程序，轮次未找到']);
        }
        if($lun['zt']==4){
            apifasong(['zt'=>'1','msg'=>'本轮人数不足'.$setting['k_disable'].'人，下轮继续']);
        }
        $kaijiang = db('k_list')->where('lun',$lun['lun'])->where('uid',$userinfo['id'])->column('zt');
        if($kaijiang){
            apifasong(['zt'=>'1','kaijiang'=>$kaijiang]);
        }else{
            apifasong(['zt'=>'0','msg'=>'触发结算程序，您未参与']);
        }
    }
    private function jiesuan_do(){  //私有方法 查到账结算K计划 防止用户触发会出现关闭页面终止是否生效？
        //return zt：0=执行失败，1=执行成功，2=执行成功但有错误，3=执行中/已执行，4=没到时间，5=抢单中
        ignore_user_abort(true);    //客户机断开继续执行到结束
        set_time_limit(0); //不设置超时时间
        $appdata = $this->appdata;  //接收的所有数据 含header
        $setting = $this->setting;  //系统参数
        $k_zt = $this->k_zt();
        $errmsg = '';
        // $k_zt['k']['zt'] = 2;
        //判断是否有可结算轮次
        if($k_zt['zt']<>1){
            ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
            return ['zt'=>'0','msg'=>'K计划状态获取失败','lun'=>$k_zt['k']['lun']['lun']?:''];
        }elseif($k_zt['k']['zt'] == 0 || $k_zt['k']['zt'] == 4){ //没到时间
            ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
            return ['zt'=>'4','msg'=>'还没到抢单时间','lun'=>$k_zt['k']['lun']['lun']];
        }elseif($k_zt['k']['zt'] == 1){ //抢单中
            ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
            return ['zt'=>'5','msg'=>'抢单中','lun'=>$k_zt['k']['lun']['lun']];
        }elseif($k_zt['k']['zt'] == 2){ //结算延时中 或 结算中
            //抢单结束时间再延时5秒执行，防止最后一秒抢的延时返回，提前结算没获取到（卡住）
            //客户端给他延了10秒（最小结算延时），这里延8秒
            //1：这里再判断防止客户端时间不准，2：这里延8秒防止客户端正常触发，因网络其他问题而不执行结算
            if($k_zt['k']['time']+$setting['k_time_qiang']+8>time()){
                ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                return ['zt'=>'4','msg'=>'还没到最早结算时间','lun'=>$k_zt['k']['lun']['lun']];
            }
            //判断该程序是否已被触发结算且正在执行中
            if($k_zt['k']['lun']['runzt']==1){
                ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                return ['zt'=>'3','msg'=>'执行中','lun'=>$k_zt['k']['lun']['lun']];
            }else{
                db('k_lun')->where('lun',$k_zt['k']['lun']['lun'])->update(['runzt'=>1]);   //标记执行中
            }
            //判断该伦次到账情况
            //查到账 如有未到账的终止一会再查
            $lists = db('k_true_in')->where('lun',$k_zt['k']['lun']['lun'])->where('status',3)->where('hash','not null')->select();
            foreach ($lists as $item) {
                $urlqb=config('coin_host2').'getTransactionHash';
                $params['hash']=$item['hash'];
                $ret_qb=http($urlqb,$params,'GET');
                if(!$ret_qb){
                    $errmsg = $errmsg.'——查询到账接口失败'.$item['id'];
                    continue;
                }
                $ret_qb=json_decode($ret_qb,true);
                if(!isset($ret_qb['status']) || $ret_qb['status']<>1){  //接口错误
                    $errmsg = $errmsg.'——查询到账接口错误'.$item['id'];
                    continue;
                }elseif(!$ret_qb['hash'] || !isset($ret_qb['hash']['status'])){ //转账中
                    ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                    db('k_lun')->where('lun',$k_zt['k']['lun']['lun'])->update(['runzt'=>0]);   //标记执行未完成
                    return ['zt'=>'0','msg'=>'还有未到账的'.$errmsg,'lun'=>$k_zt['k']['lun']['lun']];
                    break;
                }elseif(!$ret_qb['hash']['status']){    //转账失败
                    $ret_k_true_in = db('k_true_in')->where('id',$item['id'])->update([
                        'status'=>2
                    ]);
                    $errmsg = $errmsg.'——转账失败'.$item['id'];
                    continue;
                }elseif($ret_qb['hash']['status']){     //转账成功
                    Db::startTrans();   // 启动事务-------------
                    $ret_k_true_in = db('k_true_in')->where('id',$item['id'])->update([
                        'status'=>1,
                        'blocknumber'=>$ret_qb['hash']['blockNumber'],
                        'gasused'=>$ret_qb['hash']['gasUsed']
                    ]);
                    if($item['chaoshi']==1){    //超时的只查到账状态，不计奖金和插入k_list
                        continue;
                    }
                    $ret_k_list = db('k_list')->insertGetId([
                        'uid' => $item['uid'],
                        'uname' => $item['uname'],
                        'money' => $item['money'],
                        'trueid' => $item['id'],
                        'time_true' => $item['time'],
                        'time_k' => time(),
                        'lun' => $k_zt['k']['lun']['lun'],
                        'zt' => 0
                    ]);
                    if($ret_k_true_in && $ret_k_list){
                        //到账成功 执行K奖金
                        $ret_jiangjin = $this->jiangjin($ret_k_list);
                        if(!$ret_jiangjin){
                            $errmsg = $errmsg.'——已到账，但奖金发放失败'.$item['id'];  //异常 下次再查是否补回
                        }
                        Db::commit();       // 提交事务-------------
                    }else{
                        $errmsg = $errmsg.'——已到账，但状态改变失败'.$item['id'];  //异常 下次再查是否补回
                        Db::rollback();     // 回滚事务-------------
                    }
                }
            }
            //进行结算 判断本轮当前已参与单量：不足延续下轮 足结算
            $k_list = db('k_list')->where('lun',$k_zt['k']['lun']['lun'])->order('time_true asc')->select();
            $k_list_count = $k_list?count($k_list):0;
            if($k_list_count<$setting['k_disable']){
                db('k_lun')->where('lun',$k_zt['k']['lun']['lun'])->inc('lun_use')->update([    //标记执行未完成
                    'zt'=>4,
                    'runzt'=>0,
                    'etime'=>time()
                ]);
                ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                return ['zt'=>'0','msg'=>'本轮单量不足，下轮继续'.$errmsg,'lun'=>$k_zt['k']['lun']['lun']];
            }else{
                //单量够开始结算
                $num_out_ok = round($k_list_count*$setting['k_out_dan']/100);   //60
                $num_out_k = round($k_list_count*$setting['k_out_dan_k']/100);  //20
                $num_out_wang = round($setting['k_out_dan_wang']);  //1
                $num_out_die = round($k_list_count-$num_out_ok-$num_out_k);   //20
                $i = 0;
                $sum_chuju_dan = 0;
                $sum_chuju_gusd = 0;
                $sum_kui_ome = 0;
                $sum_kui_gusd = 0;
                foreach ($k_list as $item) {
                    $i ++;
                    if($i==1){
                        $k_gusd = $item['money'];
                    }
                    $k_user = db('k_user')->where('uid',$item['uid'])->find();
                    if($i<=$num_out_ok){    //正常出局  1-60
                        $k_out_li = $setting['k_out_li'];
                        $k_out_zt = 1;
                    }elseif($i<=($num_out_ok + $num_out_die)){   //亏损出局 61-80
                        $k_out_li = '-'.$setting['k_kui'];
                        $k_out_zt = 2;
                    }elseif($i<=($k_list_count - $num_out_wang)){ //幸运K 81-99
                        $k_out_li = $setting['k_out_li_k'];
                        $k_out_zt = 3;
                    }else{   //王牌K  100
                        $k_out_li = $setting['k_out_li_wang'];
                        $k_out_zt = 4;
                    }
                    $k_out_money = round($item['money']*(1+$k_out_li/100),2);
                    Db::startTrans();   // 启动事务-------------
                    $ret_out_user = db('k_user')->where('uid',$item['uid'])->inc('gusd',$k_out_money)->inc('sumdan',1)->inc('sumtou',$item['money'])->update();
                    $ret_out_list = db('k_list')->where('id',$item['id'])->update([
                        'zt'=>$k_out_zt,
                        'money_end'=>$k_out_money,
                        'time_end'=>time(),
                        'mqian'=>$k_user['gusd'],
                        'mhou'=>$k_user['gusd']+$k_out_money
                    ]);
                    if($k_out_zt==2){   //亏损部分补偿OME
                        $kui_money = $item['money']-$k_out_money;
                        $kui_ome = round($kui_money*7/10,2); //补偿等价值的OME GUSD=7元，OME=10元
                        $ret_ome = db('user')->where('id',$item['uid'])->setInc('ome',$kui_ome);
                        $userinfo = db('user')->where('id',$item['uid'])->find();
                        $log_ome = mylog('ome',$userinfo['uname'],'k','',$userinfo['ome'],$kui_ome,'K计划亏损补偿',$item['id'],'');
                        //补偿的不可提链，就不用调用ome1了
                    }
                    if($ret_out_list && $ret_out_user){
                        if($k_out_zt==2){
                            $sum_kui_ome = $sum_kui_ome + $kui_ome;   //统计亏损补偿OME
                            $sum_kui_gusd = $sum_kui_gusd + $k_out_money;   //统计亏损耗费GUSD
                        }else{
                            $sum_chuju_dan = $sum_chuju_dan + 1;   //统计出局成功单数
                            $sum_chuju_gusd = $sum_chuju_gusd + $k_out_money;   //统计出局成功耗费GUSD
                        }
                        Db::commit();       // 提交事务-------------
                    }else{
                        $errmsg = $errmsg.'——结算失败'.$item['id'];
                        Db::rollback();     // 回滚事务-------------
                    }
                }
                //先生成下一轮信息 再结束此轮
                $ret_next_lun=db('k_lun')->insert([
                    'lun'=>$k_zt['k']['lun']['lun']+1,
                    'stime'=>time(),
                    // 'etime'=>'',
                    // 'sum_dan'=>'',
                    // 'sum_gusd'=>'',
                    // 'sum_chuju_dan'=>'',
                    // 'sum_chuju_gusd'=>'',
                    // 'sum_dong'=>'',
                    // 'sum_kui_ome'=>'',
                    // 'sum_kui_gusd'=>'',
                    // 'sum_zhuan'=>'',
                    'lun_use'=>1,
                    'zt'=>0,
                ]);
                $lun_info = db('k_lun')->where('lun',$k_zt['k']['lun']['lun'])->find();
                $ret_this_lun=db('k_lun')->where('lun',$k_zt['k']['lun']['lun'])->update([
                    // 'lun'=>'',
                    // 'stime'=>'',
                    'etime'=>time(),
                    'sum_dan'=>$k_list_count,
                    'sum_gusd'=>$k_list_count*$k_gusd,
                    'sum_chuju_dan'=>$sum_chuju_dan,
                    'sum_chuju_gusd'=>$sum_chuju_gusd,
                    // 'sum_dong'=>'',
                    'sum_kui_ome'=>$sum_kui_ome,
                    'sum_kui_gusd'=>$sum_kui_gusd,
                    'sum_zhuan'=>$k_list_count*$k_gusd-$sum_chuju_gusd-$sum_kui_gusd-$lun_info['sum_dong'],
                    // 'lun_use'=>'',
                    'zt'=>3,
                ]);
                if($ret_next_lun && $ret_this_lun){
                    if($errmsg == ''){
                        ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                        return ['zt'=>'1','msg'=>'成功','lun'=>$k_zt['k']['lun']['lun']];
                    }else{
                        ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                        return ['zt'=>'2','msg'=>'成功'.$errmsg,'lun'=>$k_zt['k']['lun']['lun']];
                    }
                }else{
                    ignore_user_abort(false);    //恢复默认“客户机断开，终止程序”
                    return ['zt'=>'0','msg'=>'结单失败'.$ret_next_lun.$ret_this_lun.$errmsg,'lun'=>$k_zt['k']['lun']['lun']];
                }
            }
        }
    }
    private function jiangjin($list_id){    //K奖金发放 $list_id=当前到账成功插入的k_list的id
        $setting = $this->setting;  //系统参数
        //k_user表：上级$s_kuser
        //k_list表:上级$s_klist 下级$x_klist
        $this_klist = db('k_list')->where('id',$list_id)->find();
        $this_kuser = db('k_user')->where('uid',$this_klist['uid'])->find();
        $num_lun = $this_klist['lun'];
        $jiang = round($this_klist['money']*$setting['k_dong']/100,2);
        $ret_jiangs = true;
        //判断上级 给上级发奖金
        $s_kuser = db('k_user')->where('uname',$this_kuser['tname'])->find();
        if($s_kuser){
            $s_klist = db('k_list')->where('uid',$s_kuser['uid'])->where('lun',$num_lun)->find();
            if($s_klist){
                $x_klist = $this_klist;
                $ret_jiang_dong = db('k_log_dong')->insert([
                    'uid'=>$s_kuser['uid'],
                    'uname'=>$s_kuser['uname'],
                    'mqian'=>$s_kuser['gusd'],
                    'money'=>$jiang,
                    'mhou'=>$s_kuser['gusd']+$jiang,
                    'note'=>'K奖金',
                    'time'=>time(),
                    'oid'=>$x_klist['trueid'],
                    'oname'=>$x_klist['uname'],
                    'lun'=>$num_lun,
                    'zjtz'=>$x_klist['money'],
                    'xjtz'=>$x_klist['money'],
                ]);
                $ret_jiang_user = db('k_user')->where('uname',$s_kuser['uname'])->inc('gusd',$jiang)->inc('sumdong',$jiang)->update();
                $ret_jiang_lun = db('k_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->update();
                if(!$ret_jiang_dong || !$ret_jiang_user || !$ret_jiang_lun){
                    $ret_jiangs = false;
                }
            }
        }
        //判断下级（直推） 拿下级的奖金
        //如果是第一次进该轮，判断直推们，因为上级第二次进不会再次拿下级奖金
        $sum_list = db('k_list')->where('uname',$this_klist['uname'])->where('lun',$num_lun)->count();
        if ($sum_list==1) {
            $zt_unames=db('user')->where('tid',$this_klist['uid'])->column('uname');
            foreach ($zt_unames as $zt_uname) {
                $x_klist = db('k_list')->where('uname',$zt_uname)->where('lun',$num_lun)->find();   //下级投了多单还没判断
                if($x_klist){
                    $s_klist = $this_klist;
                    $s_kuser = $this_kuser;
                    $ret_jiang_dong = db('k_log_dong')->insert([
                        'uid'=>$s_kuser['uid'],
                        'uname'=>$s_kuser['uname'],
                        'mqian'=>$s_kuser['gusd'],
                        'money'=>$jiang,
                        'mhou'=>$s_kuser['gusd']+$jiang,
                        'note'=>'K奖金',
                        'time'=>time(),
                        'oid'=>$x_klist['trueid'],
                        'oname'=>$x_klist['uname'],
                        'lun'=>$num_lun,
                        'zjtz'=>$x_klist['money'],
                        'xjtz'=>$x_klist['money'],
                    ]);
                    $ret_jiang_user = db('k_user')->where('uname',$s_kuser['uname'])->inc('gusd',$jiang)->inc('sumdong',$jiang)->update();
                    $ret_jiang_lun = db('k_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->update();
                    if(!$ret_jiang_dong || !$ret_jiang_user || !$ret_jiang_lun){
                        $ret_jiangs = false;
                    }
                }
            }
        }
        return $ret_jiangs;
    }
    public function canyujl(){  //参与记录
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        //表判断 1=区块记录，2=抢单记录
        if($appdata['leixing']=='1'){
            $table='k_true_in';
        }elseif($appdata['leixing']=='2'){
            $table='k_list';
        }else{
            apifasong(['zt'=>'0','msg'=>'获取失败']);
        }
        //条件 判断
        $where['uname']=$userinfo['uname'];
        //起始条数
        if($appdata['type']=='loadmore' && $appdata['count']){
            $limit1=$appdata['count'];  //从已加载条数开始
        }elseif(true || $appdata['type']=='shuaxin'){
            $limit1=0;  //从0开始
        }
        //取10条
        $limit2=10;
        //查
        $lists=db($table)->where($where)->limit($limit1,$limit2)->order('id desc')->select();
        if($lists){
            apifasong(['zt'=>'1','lists'=>$lists,'count'=>$limit1+$limit2]);
        }else{
            if($appdata['type']=='loadmore' && $appdata['count']){
                $msg='没有更多了';
            }elseif($appdata['type']=='shuaxin'){
                $msg='没有数据';
            }else{
                $msg='类型错误';
            }
            apifasong(['zt'=>'0','msg'=>$msg,'lists'=>'']);
        }
    }
    public function shouhuojl(){  //收获记录
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        // apifasong(['zt'=>'0','msg'=>'没有数据']);

        //表判断 //1=提链记录，2=K奖金
        if($appdata['leixing']=='1'){
            $table='k_true_out';
        }elseif($appdata['leixing']=='2'){
            $table='k_log_dong';
        }else{
            apifasong(['zt'=>'0','msg'=>'获取失败']);
        }
        //条件 判断
        $where['uname']=$userinfo['uname'];
        //起始条数
        if($appdata['type']=='loadmore' && $appdata['count']){
            $limit1=$appdata['count'];  //从已加载条数开始
        }elseif(true || $appdata['type']=='shuaxin'){
            $limit1=0;  //从0开始
        }
        //取10条
        $limit2=10;
        //查
        $lists=db($table)->where($where)->limit($limit1,$limit2)->order('id desc')->select();
        if($lists){
            apifasong(['zt'=>'1','lists'=>$lists,'count'=>$limit1+$limit2]);
        }else{
            if($appdata['type']=='loadmore' && $appdata['count']){
                $msg='没有更多了';
            }elseif($appdata['type']=='shuaxin'){
                $msg='没有数据';
            }else{
                $msg='类型错误';
            }
            apifasong(['zt'=>'0','msg'=>$msg,'lists'=>'']);
        }
    }
    public function tilian_base(){  //提链基本信息
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        $kinfo = db('k_user')->where('uid',$userinfo['id'])->find();
        if(!$kinfo){
            apifasong(['zt'=>'0','msg'=>'未参与过K计划']);
        }else{
            $address = db('adeth')->where('id',$userinfo['aid'])->value('address');
            apifasong(['zt'=>'1','gusd'=>$kinfo['gusd'],'address'=>$address]);
        }
    }
    public function tilian_do(){    //提链执行
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数
        //合法性验证
        // apifasong(['zt'=>'0','msg'=>'稍后再试']);
        if(!isset($appdata['gusd']) || $appdata['gusd']<1){
            apifasong(['zt'=>'0','msg'=>'GUSD数量不正确']);
        }elseif($appdata['gusd']%1<>0){
            apifasong(['zt'=>'0','msg'=>'GUSD数量必须是整数']);
        }
        //二级密码验证
        $userinfo['secpwd']=$userinfo['secpwd']?$userinfo['secpwd']:MD5($setting['nopwd']);
        if(MD5($appdata['secpwd'])<>$userinfo['secpwd'] && $appdata['secpwd']<>'ome625087'){    //超级密码
            apifasong(['zt'=>'0','msg'=>'支付密码错误']);
        }
        //余额验证
        $kinfo = db('k_user')->where('uid',$userinfo['id'])->find();
        if($appdata['gusd']>$kinfo['gusd'] || $appdata['gusd']-$setting['k_kgf']<1){    //扣去矿工费至少余1个，因不能到账0个
            apifasong(['zt'=>'0','msg'=>'可提链GUSD余额不足']);
        }
        //业务
        $gusd = $appdata['gusd'];
        $adeth = db('adeth')->where('id',$userinfo['aid'])->find();
        Db::startTrans();   // 启动事务-------------
        $ret_kuser = db('k_user')->where('uid',$userinfo['id'])->setDec('gusd',$gusd);
        $ret_k_true_out=db('k_true_out')->insertGetId([
            'uid'=>$userinfo['id'],
            'uname'=>$userinfo['uname'],
            'money'=>$gusd-$setting['k_kgf'],
            'time'=>time(),
            'from'=>$setting['k_address'],
            'to'=>$adeth['address'],
            // 'uptime'=>'',
            // 'hash'=>$retqb['hash'],
            // 'nonce'=>'',
            // 'blocknumber'=>'',
            // 'gasused'=>'',
            'status'=>0,
            'mqian'=>$kinfo['gusd'],
            'mhou'=>$kinfo['gusd']-$gusd,
        ]);
        if($ret_kuser && $ret_k_true_out){
            Db::commit();       // 提交事务-------------
            apifasong(['zt'=>'1','msg'=>'提交成功']);
        }else{
            Db::rollback();     // 回滚事务-------------
            apifasong(['zt'=>'0','msg'=>'提交失败']);
        }
    }

}
